// pages/components/pageShare/pageShare.js
import { request } from "../../../utils/request"
// import { promises } from "dns";
const app=getApp()
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    requestData: {   //获取海报接口
      type: Object,
      value: {}
    },
    posterType: {
      type: String,  //海报类型
      value: ''
    },
    useLivePlugin:{ //是否使用直播插件
      type:Boolean,
      value:false
    },
    imgField:{     //预览海报时，后台返回的海报字段
      type:String,
      value:'shareImg'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    isShowshare: false,   //显示底部分享按钮
    showPoster: false,
    postImg: "",
    isShowposter: false, //canvas 海报展示
    tips:'',
    shareInfo:{}
  },
  lifetimes: {
    attached: function() {
      // 在组件实例进入页面节点树时执行
      console.log('1111')
      console.log('1111')
      var res = wx.getSystemInfoSync();
      this.setData({
        winW: res.windowWidth,
        winH: res.windowHeight
      })
      console.log('系统信息',res.windowWidth,res.windowHeight)
    },
    detached: function() {
      // 在组件实例被从页面节点树移除时执行
    },
  },
 
  /**
   * 组件的方法列表
   */
  methods: {
    showSharemodal: function () {
      this.setData({
        isShowshare: true
      })
    },
    hideSharemodal: function () {
      this.setData({
        isShowshare: false
      })
    },
    //预览海报
    previewPoster() {
      let imgField=this.data.imgField;
      request({
        data: this.data.requestData,
        useLivePlugin: this.data.useLivePlugin
      }).then(res => {
        console.log(res);
        let postImg = res.data.data[imgField]
        if (this.data.posterType) {
          this.setData({
            showPoster: true,
            postImg: postImg
          })
        } else {
          wx.previewImage({
            current: postImg,
            urls: [postImg]
          })
        }

        this.hideSharemodal()
      }).catch(err => {
        console.log(err);

      })
    },
    closeLivePoster() {
      this.setData({
        showPoster: false,
      })
    },
    // 直播保存海报
    savePoster() {
      var that = this;
      wx.downloadFile({
        url: this.data.postImg, //仅为示例，并非真实的资源
        success: (res) => {
          // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
          if (res.statusCode === 200) {
            wx.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success(res1) {
                console.log('保存成功', res1)
                wx.showToast({
                  title: '保存成功',
                })
                that.setData({
                  showPoster: false,
                })
              },
              fail(res1) {
                console.log('保存失败', res1)
                wx.openSetting({
                  complete: (res) => { },
                })
              }
            })
          }
        },
        fail: (res) => {
          wx.showToast({
            title: '图片下载失败',
            icon:'none'
          })
        }
      })

    },
    // canvas海报展示
    showPoster: function () {
      var that = this;
      that.setData({
        isShowposter: true,
      })
      var isDrawfinish = that.data.isDrawfinish;
      if (isDrawfinish) { return; }
      this.requestShareinfo(this.data.requestData);
    },
    hidePoster: function () {
      var that = this;
      that.setData({
        isShowposter: false,
      })
    },
    showDistriPoster(){
      this.requestShareinfo(this.data.requestData);
    },
    // 宣传海报
    requestShareinfo: function (requestData) {
      var _this = this;
      
      //发起请求，获取列表列表

      wx.showLoading({
        title: '海报绘制中',
      })
      wx.request({
        url: app.globalData.requestUrl,
        data: requestData,
        success: function (res) {
          if (res.data.ec == 200) {
            console.log(res.data.data);
            var shareInfo = res.data.data;
            shareInfo.type = requestData.type;
            console.log(shareInfo);
            // _this.downImage(shareInfo, requestData.type);
            _this.downImageNew(shareInfo,'cover').then(
              ()=>_this.downImageNew(shareInfo,'qrcode'),
              
            ).then(
              ()=>_this.downImageNew(shareInfo,'shopLogo'),
              
            ).then(
              ()=>{
                shareInfo.price = "￥" + shareInfo.price + " 扫码购买"
                _this.setData({
                  shareInfo:shareInfo
                })
                _this.createCanvas(requestData.type)
              },
              err => {
                console.log("rejected: ", err)
                _this.setData({
                  isDrawfinish: false,
                  tips: err
                })
                wx.hideLoading()
              }
            )
          } else {
            wx.showToast({
              title: res.data.em,
              icon:'none'
            })
            
          }
        },
        complete: function () {
          // wx.hideLoading();
        }
      });
    },
    downImageNew(shareInfo,imgType){
      var errtip="",_this=this
      return new Promise(function(resolve,reject){
        if(!shareInfo[imgType]){
          switch(imgType){
            case 'cover':
              errtip="封面不存在"
              break;
            case 'qrcode':
              errtip="小程序码不存在"
            break;
            case 'shoplogo':
              errtip="店主太忙了，还没来及上传LOGO。\n您可以偷偷告诉店主：\n小程序后台右上角-> 店铺设置 -> 上传店铺logo"
            break;
          }
          
          reject(errtip)
          return
        }
        wx.downloadFile({
          url: shareInfo[imgType], //仅为示例，并非真实的资源
          success (res) {
            // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
            // console.log('下载图片',res)
            if (res.statusCode === 200) {
              shareInfo[imgType]=res.tempFilePath
              _this.setData({
                shareInfo:shareInfo
              })
              resolve()
            }else{
              showErrorTip()
              reject(errtip)
            }
          },fail(){
            showErrorTip()
            reject(errtip)
          }
        })
      })
      function showErrorTip(){
        switch(imgType){
          case 'cover':
            errtip="封面下载失败"
            break;
          case 'qrcode':
            errtip="小程序码下载失败"
          break;
          case 'shoplogo':
            errtip="店铺logo下载失败"
          break;
        }
        console.log('下载失败')
        
      }
    },
    // downImage: function (shareInfo,  posterType) {
    //   var that = this;
    //   if (shareInfo.qrcode == '') {
    //     that.setData({
    //       isDrawfinish: false,
    //       tips: "封面不存在"
    //     })
    //     wx.hideLoading();
    //     return;
    //   }
    //   wx.downloadFile({
    //     url: shareInfo.cover,
    //     success: function (res1) {
    //       if (res1.statusCode == 200) {
    //         console.log(res1);
    //         shareInfo.cover = res1.tempFilePath;
    //         if (shareInfo.qrcode == '') {
    //           that.setData({
    //             isDrawfinish: false,
    //             tips: "小程序码不存在"
    //           })
    //           wx.hideLoading();
    //           return;
    //         }
    //         wx.downloadFile({
    //           url: shareInfo.qrcode,
    //           success: function (res2) {
    //             if (res2.statusCode == 200) {
    //               console.log(res2.tempFilePath);
    //               shareInfo.qrcode = res2.tempFilePath;
    //               if (shareInfo.shopLogo == '') {
    //                 that.setData({
    //                   isDrawfinish: false,
    //                   tips: "店主太忙了，还没来及上传LOGO。\n您可以偷偷告诉店主：\n小程序后台右上角-> 店铺设置 -> 上传店铺logo"
    //                 })
    //                 wx.hideLoading();
    //                 return;
    //               }
    //               wx.downloadFile({
    //                 url: shareInfo.shopLogo,
    //                 success: function (res3) {
    //                   console.log(res3);
    //                   if (res3.statusCode == 200) {
    //                     console.log(res3.tempFilePath);
    //                     shareInfo.shopLogo = res3.tempFilePath;
    //                     shareInfo.price = "￥" + shareInfo.price + " 扫码购买";
    //                     that.setData({
    //                       shareInfo: shareInfo
    //                     });
    //                     that.createCanvas(posterType);
    //                   } else {
    //                     console.log("Logo不存在");
    //                     that.setData({
    //                       isDrawfinish: false,
    //                       tips: "Logo不存在"
    //                     })
    //                     wx.hideLoading();
    //                   }
    //                 },
    //                 fail: function () {
    //                   console.log("第三张图片下载失败");
    //                   that.setData({
    //                     isDrawfinish: false,
    //                     tips: "店主太忙了，还没来及上传LOGO。\n您可以偷偷告诉店主：\n小程序后台右上角-> 店铺设置 -> 上传店铺logo"
    //                   })
    //                   wx.hideLoading();
    //                 }
    //               })
    //             } else {
    //               console.log("小程序码不存在");
    //               that.setData({
    //                 isDrawfinish: false,
    //                 tips: "小程序码不存在"
    //               })
    //               wx.hideLoading();
    //             }
    //           },
    //           fail: function () {
    //             console.log("第二张图片下载失败");
    //             that.setData({
    //               isDrawfinish: false,
    //               tips: "小程序码下载失败"
    //             })
    //             wx.hideLoading();
    //           }
    //         })
    //       } else {
    //         console.log("封面不存在");
    //         that.setData({
    //           isDrawfinish: false,
    //           tips: "封面不存在"
    //         })
    //         wx.hideLoading();
    //       }
    //     },
    //     fail: function () {
    //       console.log("第一张图片下载失败");
    //       that.setData({
    //         isDrawfinish: false,
    //         tips: "封面下载失败"
    //       })
    //       wx.hideLoading();
    //     }
    //   })
    // },
    createCanvas: function (posterType) {
      var that = this;
      var shareInfo = that.data.shareInfo;
      console.log(shareInfo);
     
        const ctx = wx.createCanvasContext('myCanvas',this);
      
      
      var winW = that.data.winW;
      console.log(winW)
      var shareDesc = shareInfo.shareDesc;
      var shareDescArr = [];
      var singleTxtnum = Math.floor((winW * 0.9 * 0.8 - 30) / 15);
      if (posterType == 'distri') {
        singleTxtnum = Math.floor((winW * 0.82 - 30) / 15);
      }
      var txtLinenum = Math.ceil(shareDesc.length / singleTxtnum) <= 2 ? Math.ceil(shareDesc.length / singleTxtnum) : 2;
      for (var i = 0; i < txtLinenum; i++) {
        var length = shareDescArr.length;
        var txtObj = shareDesc.substring(length * singleTxtnum, length * singleTxtnum + singleTxtnum);
        shareDescArr.push(txtObj);
      }
      shareInfo.shareDesc = shareDescArr;
      var canvasW = winW * 0.9 * 0.8;
      var canvasH = winW * 0.9 * 0.8 + shareDescArr.length * 15 * 1.3 + canvasW * 0.34 + 54;
      if (posterType == 'distri') {
        canvasW = winW * 0.82;
        canvasH = winW * 0.82 + shareDescArr.length * 15 * 1.3 + canvasW * 0.34 + 54;
      }
      if (shareInfo.type == 'news') {
        canvasH = (canvasW - 30) * 14 / 25 + 30 + shareDescArr.length * 15 * 1.3 + canvasW * 0.34 + 54;
      }
      that.setData({
        canvasW: canvasW,
        canvasH: canvasH
      })

      console.log("画布宽" + canvasW)
      if (posterType == 'distri') {
        var x = 0, y = 0, radius = 5, width = canvasW, height = canvasH;
        ctx.rect(0, 0, canvasW, canvasH)
        ctx.setFillStyle('#ffffff')
        ctx.fill()
        ctx.save()
        ctx.beginPath()
        ctx.moveTo(x + radius, y);
        ctx.lineTo(x + width - radius, y);
        ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
        ctx.lineTo(x + width, y + height - radius);
        ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
        ctx.lineTo(x + radius, y + height);
        ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
        ctx.lineTo(x, y + radius);
        ctx.quadraticCurveTo(x, y, x + radius, y);
        ctx.closePath();
        ctx.clip()
      } else {
        ctx.rect(0, 0, canvasW, canvasH)
        ctx.setFillStyle('#ffffff')
        ctx.fill()
      }
      var imgW = canvasW - 30;
      var imgH = canvasW - 30;
      if (shareInfo.type == 'news') {
        imgH = imgW * 14 / 25;
      }
      console.log("图片宽" + imgW)
      ctx.drawImage(shareInfo.cover, 15, 15, imgW, imgH)
      ctx.setFontSize(15)
      for (var i = 0; i < shareDescArr.length; i++) {
        var textY = (imgH + 30) + i * 15 * 1.2 + 10;
        ctx.setFillStyle('#333333');
        ctx.fillText(shareDescArr[i], 15, textY);
      }
      var priceY = (imgH + 30) + shareDescArr.length * 15 * 1.3 + 14;
      if (shareInfo.type == 'news') {
        priceY = (imgH + 30) + shareDescArr.length * 15 * 1.3;
      }
      ctx.setFillStyle('#ff2020');
      ctx.setFontSize(15);
      if (shareInfo.type != 'news') {
        ctx.fillText(shareInfo.price, 15, priceY);
      }
      var lineY = priceY + 16;
      ctx.moveTo(20, lineY);
      ctx.lineTo(canvasW - 30, lineY);
      ctx.setStrokeStyle('#eeeeee');
      ctx.stroke();
      ctx.drawImage(shareInfo.qrcode, 15, lineY + 10, canvasW * 0.34, canvasW * 0.36);
      ctx.setFontSize(12);
      ctx.setFillStyle('#999999');
      ctx.fillText('长按识别小程序码访问', canvasW * 0.36 + 23, lineY + canvasW * 0.36 * 0.34 + 10);
      ctx.drawImage(shareInfo.shopLogo, canvasW * 0.36 + 25, lineY + canvasW * 0.36 * 0.32 + 22, canvasW * 0.10, canvasW * 0.10);
      var shopName = shareInfo.shopName;
      var shopNameArr = [];
      var txtLinenum = Math.ceil(shopName.length / 9) <= 2 ? Math.ceil(shareDesc.length / 9) : 2;
      for (var i = 0; i < txtLinenum; i++) {
        var length = shopNameArr.length;
        var txtObj = shopName.substring(length * 9, length * 9 + 9);
        shopNameArr.push(txtObj);
      }
      if (shopName.length <= 9) {
        ctx.fillText(shareInfo.shopName, canvasW * 0.36 + 30 + canvasW * 0.10, lineY + canvasW * 0.36 * 0.32 + 22 + canvasW * 0.06);
      } else {
        for (var i = 0; i < shopNameArr.length; i++) {
          var textY = (lineY + canvasW * 0.36 * 0.32 + 22) + i * 12 * 1.2 + 10;
          ctx.fillText(shopNameArr[i], canvasW * 0.36 + 30 + canvasW * 0.10, textY);
        }
      }
      ctx.draw();
      console.log('测试canvas')
      wx.hideLoading();
      that.setData({
        isDrawfinish: true
      })
    },
    saveImage: function () {
     
      var canvasW = this.data.canvasW;
      var canvasH = this.data.canvasH;
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: canvasW,
        height: canvasH,
        canvasId: 'myCanvas',
        fileType: 'jpg',
        success: function (res) {
          console.log(res.tempFilePath)
          var tempFilePathShow = res.tempFilePath;
          wx.showLoading({
            title: '正在保存',
            mask: true,
            time: 100000
          })
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePathShow,
            success(res) {
              console.log(res);
              wx.showToast({
                title: '图片保存成功',
                icon:'none'
              })
              
            },
            fail(f) {
              wx.showToast({
                title: '图片保存失败',
                icon:'none'
              })
            },
            complete() {
              wx.hideLoading();
            }
          })
        },
        fail(err){
          console.log(err)
        }
      },this)
    },
  }
})
